const path = require('path')
const scpClient = require('scp2')
const Client = require('ssh2').Client
const inquirer = require('inquirer') // 用于命令行交互
const FileSystem = require('./utils/filesys')
const fileSys = new FileSystem() // 用于统一文件数量
const ora = require('ora')
const chalk = require('chalk')
// 打包输出路径
const { publicPath } = require('./index')
// 服务器配置项
const servers = require('./serverConf')
const serverList = Object.keys(servers) // 用于选择要发布到的服务器

/**
 * 命令行交互配置项，选择要发布的模块
 */
const question = [
	{
		type: 'list',
		name: 'server',
		message: '请选择要发布到目标服务器',
		choices: serverList
	}
]
/**
 * 选择指定模块并发布
 */
inquirer.prompt(question).then(async answer => {
	// 整理所选目标服务器配置项
	const activeServer = servers[answer.server]

	const from = path.join(__dirname, '../dist' + (publicPath ? publicPath + '/' : ''))
	const to = activeServer.path + (publicPath ? publicPath + '/' : '')
	sftpSend(from, to, activeServer)
})

function sftpSend(from, to, activeServer) {
	const filesLength = fileSys.totalFilesByDir(from) // 待上传文件总数
	console.log(chalk.blue(`上传文件数量为：${filesLength}个`))
	const spinner = ora('正在发布到服务器...')

	const conn = new Client()
	conn
		.on('ready', function () {
			console.log(chalk.red(`本地路径: ${from}\n目标路径: ${to}`))
			// rm 删除dist文件，\n 是换行 换行执行 重启nginx命令 我这里是用docker重启nginx
			conn.exec('rm -rf ' + to + '\ndocker restart nginx', function (err, stream) {
				if (err) throw err
				stream
					.on('close', function (code, signal) {
						// 在执行shell命令后，把开始上传部署项目代码放到这里面
						spinner.start()
						scpClient.scp(
							from,
							{
								host: activeServer.host,
								port: activeServer.port,
								username: activeServer.username,
								password: activeServer.password,
								path: to
							},
							function (err) {
								spinner.stop()
								if (err) {
									console.log(chalk.red('发布失败.\n'))
									throw err
								} else {
									console.log(chalk.green('Success! 成功发布到服务器! \n'))
								}
							}
						)

						conn.end()
					})
					.on('data', function (data) {
						console.log('STDOUT: ' + data)
					})
					.stderr.on('data', function (data) {
						console.log('STDERR: ' + data)
					})
			})
		})
		.connect({
			host: activeServer.host,
			port: activeServer.port,
			username: activeServer.username,
			password: activeServer.password
			// privateKey: require('fs').readFileSync('/home/admin/.ssh/id_dsa')
		})
}
